import {Utils, WebStorage} from "jboot-env";
import table from './table';
import useRouterLoad from './load';

export default function (config, options) {
	const { http, store } = options.getInstance();

	const {loadUser, loadMenus} = useRouterLoad(http, store);

	config.table(table).check(function (permissionCode, to, callback) {
		const {menus} = store.getters;

		if(permissionCode === '*'){
			callback();
		}else{
			WebStorage.localMode().get('{PROJECT_NAME}-token').then(loadUser).then(() => {
				if(Utils.isNotEmpty(menus)){
					checkHandler(permissionCode, to, callback, menus);
				}else{
					clearMenuList();

					loadMenus().then(menus => {
						if(Utils.isEmpty(menus)){
							callback('fail');
						}else{
							checkHandler(permissionCode, {name: menus[0].code}, callback, menus);
						}
					});
				}
			}).catch(() => callback('login'));
		}
	}).after(function (route) {
		const vm = options.getInstance().vue;

		const {name, matched} = route;

		const title = Utils.blank2Default(matched, []).map(item => item.meta?.title).reverse().filter(Boolean).join('_')

		vm.$nextTick(function () {
			vm.$bus.emit('update.document.title', {
				name,
				title
			});

			vm.$bus.emit('layout.content.scroll.top');
		});
	})
}

let menuList = [], codeGroup = {};

function clearMenuList() {
	menuList = [];
}

//将服务器返回的菜单转换为map，key值为权限编码。
function createMenuCodeMap(menus) {
	if(menuList.length > 0) return;

	menuList = Utils.tree2List(menus);

	codeGroup = menuList.reduce(function (result, current) {
		return {...result, [current.code]: current};
	}, {});
}

//判断是否有权限访问页面
function checkHandler(permissionCode, to, callback, menus) {
	if(permissionCode){
		createMenuCodeMap(menus);

		if(permissionCode in codeGroup){
			callback();
		}else{
			callback(false);
		}
	}else{
		callback();
	}
}
